/**
 * @description 4个输入框事件模板
 * @example 因子重大变化
 * @author muisuidaan
 */

import styled from "styled-components";


import SInputNumber from '../Input/InputNumber'

import { Fragment, useEffect, useState } from "react";
import { RedBtn } from "../Button";
import { BottomCard } from './BottomCard';
import { RedTitle } from "../Title/redTitile";

import {ToFixNumber} from "@/utils/utils"
import { collectErrors } from './InlineInput'

// 适合此模板的事件代码
export const EVENT_INLINE_INPUT = [
  'stock_factor_alert', // 因子重大变化-个基
]
const Box = styled.div`
  width: 100%;
  background: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  padding: 12px;
  color: #35425E;
  margin-top: 8px;
`;
export const FlexDiv = styled.div`
  display: flex;
  align-items: center;
  margin-top: ${(props) => props.mt || "0"};
`;



const MultipleInput = (props: any) => {
  const { thresholdValue, onSubmit,eventInfo, enable } = props;
  const [saveParams, setSaveParams] = useState({
    momentumThreshold: "",
    qualityThreshold: "",
    growthThreshold: "",
    valuationThreshold: "",
  });

  const [isChanged, setIsChanged] = useState(false);
  const [errorList, setErrorList] = useState([]);

  useEffect(() => {
    setSaveParams({
      momentumThreshold: thresholdValue?.momentumThreshold,
      qualityThreshold: thresholdValue?.qualityThreshold,
      growthThreshold: thresholdValue?.growthThreshold,
      valuationThreshold: thresholdValue?.valuationThreshold,
    });
    setErrorList([])
    setIsChanged(false)
  }, [thresholdValue]);

  useEffect(() => {
    if(enable !== undefined && enable !== eventInfo?.enable) {
      setIsChanged(true)
    }
  },[enable])

  const onChange = (val: string | number | null, key: string) => {
    handleCollectErrors(val?.toString(), key)
    setIsChanged(true)
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || '',
      }
    })
  }

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res: string[] = collectErrors(val, key, errorList, saveParams)
    setErrorList([...new Set(res)])
    return [...new Set(res)];
  }

  const onClick = () => {
    const res = handleCollectErrors();
    console.log('res',res,errorList.length > 0 || res.length > 0);

    if (errorList.length > 0 || res.length > 0|| !isChanged) return;
    onSubmit({
      id: parseFloat(eventInfo.key),
      preValue: saveParams,
      dataMemo:createInfoText(false)
    });
  };
  console.log(errorList);

  //通过参数生成说明文案
  const createInfoText = (html:boolean)=>{
    let str = `<p>* 对基金的股票仓位因子值进行监控，其中动量因子变动幅度超过 <em>${ ToFixNumber(saveParams?.momentumThreshold)}</em> ；质量因子变化幅度超过 <em>${ ToFixNumber(saveParams?.qualityThreshold)} </em> ；成长因子变化幅度超过 <em>${ ToFixNumber(saveParams?.growthThreshold)}</em> ；估值因子变化幅度超过 <em>${ ToFixNumber(saveParams?.valuationThreshold)}</em> 。</p>`
    if(!html){
      str = str
      .replaceAll('<p>', '')
      .replaceAll('</p>', '')
      .replaceAll('<em>', '')
      .replaceAll('</em>', '')
      .replace(/\s+/g,"")
    }
    
    
    return str
  }
  return (
    <Fragment>
      <Box>
        <FlexDiv>
          <span>动量因子变化幅度阈值</span>
          <SInputNumber
            value={saveParams.momentumThreshold}
            isError={errorList.includes("momentumThreshold")}
            onChange={(e) => onChange(e, "momentumThreshold")}
            min= {Number.MIN_SAFE_INTEGER}
            max={Number.MAX_SAFE_INTEGER}
            precision={2}

            // step={ '0.00'}
            // controls={false}
          />
        </FlexDiv>
        <FlexDiv mt="8px">
          <span>质量因子变化幅度阈值</span>
          <SInputNumber
            value={saveParams.qualityThreshold}
            isError={errorList.includes("qualityThreshold")}
            onChange={(e) => onChange(e, "qualityThreshold")}
            min= {Number.MIN_SAFE_INTEGER}
            max={Number.MAX_SAFE_INTEGER}
            precision={2}

            // step={ '0.00'}
            // controls={false}
            // formatter={(val) =>{
            //   return parseFloat(val).toFixed(2);

            // }}
            // parser={(val) =>{
            //   return parseFloat(val).toFixed(2);
            // }}

          />
        </FlexDiv>
        <FlexDiv mt="8px">
          <span>成长因子变化幅度阈值</span>
          <SInputNumber
            value={saveParams.growthThreshold}
            isError={errorList.includes("growthThreshold")}
            onChange={(e) => onChange(e, "growthThreshold")}
            min= {Number.MIN_SAFE_INTEGER}
            max={Number.MAX_SAFE_INTEGER}
            precision={2}

            // unit="%"
            // step={ '0.00'}
            // controls={false}

          />
        </FlexDiv>
        <FlexDiv mt="8px">
          <span>估值因子变化幅度阈值</span>
          <SInputNumber
            value={saveParams.valuationThreshold}
            isError={errorList.includes("valuationThreshold")}
            onChange={(e) => onChange(e, "valuationThreshold")}
            min= {Number.MIN_SAFE_INTEGER}
            max={Number.MAX_SAFE_INTEGER}
            precision={2}
            // step={ '0.00'}
            // controls={false}

          />
        </FlexDiv>
        {/* 底部说明文案 */}
        <BottomCard 
          info={createInfoText(true)}
        ></BottomCard>

      </Box>
      <FlexDiv style={{ marginTop: 12,alignItems:'flex-end' }}>
        <RedBtn  disabled={!isChanged} onClick={onClick}>
          确定
        </RedBtn>
        {/* 按钮说明文案 */}
        {isChanged&&<RedTitle eventInfo={eventInfo}></RedTitle>}
      </FlexDiv>

      

    </Fragment>
  );
};

export default MultipleInput;
